#!/usr/lib/python
# -*- coding: utf-8 -*-

import urllib2
from sgmllib import SGMLParser
from datetime import datetime
from xmlrpclib import ServerProxy
from code import interact

class URLListener(SGMLParser):
    def reset(self):
        SGMLParser.reset(self)
        self.is_content = 0
        self.attrs = []
        self.table_index = 0
        self.td_index = 0
        self.items = []
        self.earthquakes = []

    def start_table(self, attr):
        for k,v in attr:
            if k == "cellspacing" and v == "1":
                self.table_index = self.table_index + 1
                if self.table_index > 1:
                    break

    def start_td(self, attr):
        for k, v in attr:
            if k == "valign" and v == "top":
                self.td_index = self.td_index + 1
                
        div = [v for k,v in attr if k == "valign" and v == "top"]
        if div:
            self.is_content = 1
            self.attrs.append("{{ %(attr)s }}" % locals())

    def end_td(self):
        self.is_content = 0

    def handle_data(self, text):
        if self.is_content and self.table_index == 1:
            if text == 'MAP':
                self.items = []
            self.items.append(text.strip())
            if len(self.items) == 7:
                self.earthquakes.append(self.items)


def earthquake_tip():
    url = "http://earthquake.usgs.gov/earthquakes/recenteqsww/Quakes/quakes_all.php"
    f = urllib2.urlopen(url)
    content_list = f.readlines()
    content = "".join(content_list)
    parser = URLListener()
    parser.feed(content)
    latest_earthquakes = parser.earthquakes
    now = datetime.now()
    utc_now = now.utcnow()
    for eq in latest_earthquakes:
        eq_time = datetime.strptime(eq[2], "%Y/%m/%d %H:%M:%S")
        delta = utc_now - eq_time
        if delta.seconds / 3600 >= 1 and float(eq[1]) > 5:
            print tip(eq[1], eq_time, eq[5], eq[6])

def tip(level, place):
    s = ServerProxy('http://125.77.200.19:8003/sms/transfer/')
    gmt = eqtime + timedelta(hours=8)
    eq_time = gmt.strftime("%Y-%m-%d %H:%M:%S")
    return s.trans(unicode(18950175194), unicode(13581868450), unicode("tip! %s Beijing Time, %s, a magnitude %s earthquake occurred. A depth of %s km." % (eq_time, place, level, depth)))

earthquake_tip()
